//
//  PayOrderCell.m
//  dyseller
//
//  Created by 红喇叭 on 2017/8/21.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "PayOrderCell.h"
#import "PayOrderDetails.h"
#import "RefundView.h"
@implementation PayOrderCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        [self initView];
    }
    return self;
}

- (void)initView{
    
    
    _oredernumber = [[UILabel alloc] init];
    _oredernumber.font = font14;
    _oredernumber.textColor = UIColorFromRGB(0x333333);
   
    [self.contentView addSubview:_oredernumber];
    _oredernumber.sd_layout.topSpaceToView(self.contentView, 12).leftSpaceToView(self.contentView, GETWITH(30)).rightSpaceToView(self.contentView, GETWITH(150)).autoHeightRatio(0);
    
    _siteView = [[UIView alloc] init];
    _siteView.backgroundColor = UIColorFromRGB(0xff9f4a);
    [self.contentView addSubview:_siteView];
    _siteView.sd_layout.rightSpaceToView(self.contentView, GETWITH(30)).topSpaceToView(self.contentView, 0).widthIs(GETWITH(120)).heightIs(GETNEWHEIGHT(100));
    UILabel *dianc = [[UILabel alloc] init];
    dianc.text = @"点餐";
    dianc.font = font15;
    dianc.textColor = [UIColor whiteColor];
    [_siteView addSubview:dianc];
    dianc.textAlignment = NSTextAlignmentCenter;
    dianc.sd_layout.topSpaceToView(_siteView, GETNEWHEIGHT(14)).widthRatioToView(_siteView, 1).leftSpaceToView(_siteView, 0).autoHeightRatio(0);
    
    _siteNumber = [[UILabel alloc] init];
    _siteNumber.font = [UIFont fontWithName:@"Helvetica-Bold" size:20*H];
    _siteNumber.textColor = [UIColor whiteColor];
    _siteNumber.textAlignment = NSTextAlignmentCenter;
    [_siteView addSubview:_siteNumber];
    
    _siteNumber.sd_layout.bottomSpaceToView(_siteView, GETNEWHEIGHT(4)).widthRatioToView(_siteView, 1).leftSpaceToView(_siteView, 0).autoHeightRatio(0);
    _userName = [[UILabel alloc] init];
    
    _userName.font = font15;
    _userName.textColor = _oredernumber.textColor;
    
    [self.contentView addSubview:_userName];
    _userName.sd_layout.leftSpaceToView(self.contentView, GETWITH(30)).topSpaceToView(_oredernumber, 5).widthIs(0).heightIs(20);
    [_userName setSingleLineAutoResizeWithMaxWidth:GETWITH(350)];
    
    
    _userID = [[UILabel alloc] init];
    
    _userID.font = _oredernumber.font;
    _userID.textColor = _oredernumber.textColor;
    
    [self.contentView addSubview:_userID];
    _userID.sd_layout.leftSpaceToView(_userName, GETWITH(30)).topEqualToView(_userName).rightSpaceToView(self.contentView, GETWITH(10)).heightIs(20);
    
    UIImageView *tellImg = [[UIImageView alloc] init];
    tellImg.image = [UIImage imageNamed:@"dingd_icon6_default_nor.png"];
    [self.contentView addSubview:tellImg];
    tellImg.sd_layout.leftEqualToView(_userName).topSpaceToView(_userName, 5).widthIs(GETWITH(30)).heightEqualToWidth();
    
    _iPhoneNum = [[UILabel alloc] init];
    _iPhoneNum.font = font15;
    _iPhoneNum.textColor = _oredernumber.textColor;

    [self.contentView addSubview:_iPhoneNum];
    _iPhoneNum.sd_layout.leftSpaceToView(tellImg,GETWITH(28)).centerYEqualToView(tellImg).widthIs(0).heightIs(20);
     [_iPhoneNum setSingleLineAutoResizeWithMaxWidth:GETWITH(400)];

    _state = [[UILabel alloc] init];
    _state.font = _oredernumber.font;
    _state.textAlignment = NSTextAlignmentRight;
    _state.textColor = _oredernumber.textColor;
    [self.contentView addSubview:_state];
    _state.sd_layout.
    rightSpaceToView(self.contentView, GETWITH(30))
    .centerYEqualToView(_iPhoneNum)
    .widthIs(GETWITH(240))
    .autoHeightRatio(0);
    
    UILabel *incomeT = [[UILabel alloc] init];
    incomeT.text = @"本单预计收入";
    incomeT.textColor = _oredernumber.textColor;
    incomeT.font = [UIFont fontWithName:@"Helvetica-Bold" size:16*H];
    [self.contentView addSubview:incomeT];
    incomeT.sd_layout.leftEqualToView(_userName).topSpaceToView(_iPhoneNum, 5).widthIs(0).heightIs(20);
    [incomeT setSingleLineAutoResizeWithMaxWidth:GETWITH(400)];
    
    _yjmoney = [[UILabel alloc] init];
    _yjmoney.textAlignment = NSTextAlignmentRight;
    _yjmoney.font = incomeT.font;
    _yjmoney.textColor = _oredernumber.textColor;
    
    [self.contentView addSubview:_yjmoney];
    _yjmoney.sd_layout.rightSpaceToView(self.contentView, GETWITH(30)).topEqualToView(incomeT).widthIs(GETWITH(200)).heightIs(20);
    
    _incomeMoney = [[UILabel alloc] init];
    _incomeMoney.font = font14;
    _incomeMoney.textColor = _oredernumber.textColor;
    
   
    [self.contentView addSubview:_incomeMoney];
    _incomeMoney.sd_layout.leftEqualToView(_userName).topSpaceToView(incomeT, 5).widthIs(0).heightIs(20);
    [_incomeMoney setSingleLineAutoResizeWithMaxWidth:GETWITH(540)];
    
    _incomeIntegral = [[UILabel alloc] init];
    _incomeIntegral.font = _incomeMoney.font;
    _incomeIntegral.textColor = UIColorFromRGB(0xfd5974);
    
    [self.contentView addSubview:_incomeIntegral];
    _incomeIntegral.sd_layout.leftSpaceToView(_incomeMoney, GETWITH(4)).topEqualToView(_incomeMoney).rightSpaceToView(self.contentView, 0).heightIs(20);
    
    _bottmV = [[UIView alloc] init];
    _bottmV.backgroundColor = UIColorFromRGB(0xdddddd);
    [self.contentView addSubview:_bottmV];
    _bottmV.sd_layout.rightSpaceToView(self.contentView, 0).bottomSpaceToView(self.contentView, 0).leftSpaceToView(self.contentView, 2).heightIs(85);
    
    
    
    
    _top1V = [[UIView alloc] init];
    _top1V.backgroundColor = [UIColor whiteColor];
    [_bottmV addSubview:_top1V];
    _top1V.sd_layout.leftEqualToView(_bottmV).topSpaceToView(_bottmV, 0).rightEqualToView(_bottmV).heightIs(45);
    
    UIView *line2V = [[UIView alloc] init];
    line2V.backgroundColor = [UIColor blackColor];
    [_top1V addSubview:line2V];
    line2V.sd_layout.rightSpaceToView(_top1V,0).topSpaceToView(_top1V,0).leftEqualToView(incomeT).heightIs(0.5);
    
    _printBtn = [[UIButton alloc] init];
    [_top1V addSubview:_printBtn];
    _printBtn.sd_layout.rightSpaceToView(_top1V, GETWITH(30)).centerYEqualToView(_top1V).widthIs(60).heightIs(30);
    _printBtn.titleLabel.font = font14;
    [_printBtn setTitle:@"打印" forState:0];
    [_printBtn setTitleColor:UIColorFromRGB(0xfe9265) forState:0];
    [_printBtn setBackgroundImage:[UIImage imageNamed:@"dingd_pirnter_btn01_default"] forState:0];
    [_printBtn addTarget:self action:@selector(stampOrder) forControlEvents:UIControlEventTouchUpInside];
    
    _refundBtn = [[UIButton alloc] init];
    [_top1V addSubview:_refundBtn];
    _refundBtn.sd_layout.rightSpaceToView(_printBtn, GETWITH(30)).centerYEqualToView(_top1V).widthIs(60).heightIs(30);
    _refundBtn.titleLabel.font = font14;
    [_refundBtn setTitle:@"退款" forState:0];
    [_refundBtn setTitleColor:UIColorFromRGB(0xfe9265) forState:0];
    [_refundBtn setBackgroundImage:[UIImage imageNamed:@"dingd_pirnter_btn01_default"] forState:0];
    [_refundBtn addTarget:self action:@selector(addRefundView) forControlEvents:UIControlEventTouchUpInside];
    
    _time = [[UILabel alloc] init];
    _time.textColor = [UIColor grayColor];
    _time.font = font14;
    _time.textAlignment = NSTextAlignmentCenter;
    [_bottmV addSubview:_time];
    
    _time.sd_layout.rightSpaceToView(_bottmV, 0).topSpaceToView(_top1V, 5).leftSpaceToView(_bottmV, 2).heightIs(20);
    
    
    
    UIView *bottomV = [[UIView alloc] init];
    bottomV.backgroundColor = [UIColor grayColor];
   // [self.contentView addSubview:bottomV];
    bottomV.sd_layout.leftEqualToView(_time).rightSpaceToView(self.contentView, 0).topSpaceToView(_time, 2).heightIs(0.5);

}

- (void)setData:(NSDictionary *)data{
    _data = data;
    
    NSMutableDictionary *dic = _data.mutableCopy;
    NSArray *array = dic[@"goods_list"];
    
     _oredernumber.text = [NSString stringWithFormat:@"订单号：%@",dic[@"order_sn"]];
    
    _time.text = [NSString stringWithFormat:@"使用日期:%@",[ToolClass strToTime:dic[@"add_time"] format:@"yyyy-MM-dd HH:mm:ss"]];
    
    if(array.count >0 ){
        if([dic[@"received"] isEqualToString:@"0"]){
            _state.text = @"未使用";
            _time.text = [NSString stringWithFormat:@"下单日期:%@",[ToolClass strToTime:dic[@"add_time"] format:@"yyyy-MM-dd hh:mm"]];
        }else if([dic[@"received"] isEqualToString:@"1"]){
            _state.text = @"已使用";
        }
    }else{
            _state.text = @"已使用";
        }
    if ([dic[@"is_refund"] isEqualToString:@"1"]){
    #pragma  mark ========已退款========
        _state.text = [NSString stringWithFormat:@"已退款(￥%@)",dic[@"refund_money"]];
    }

    _userName.text = [NSString stringWithFormat:@"%@",dic[@"nickname"]];
    if(_userName.text.length<1){
        _userName.text = @"该用户没有名字";
    }
    if(((NSString*)dic[@"phone"]).length>0){
      _iPhoneNum.text = dic[@"phone"];
    }else{
        _iPhoneNum.text = @"该用户未绑定手机";
    }
    
    
     _userID.text = [NSString stringWithFormat:@"ID:%@",dic[@"user_id"]];

    _yjmoney.text = [NSString stringWithFormat:@"￥%@",dic[@"real_money"]];
    
     _incomeMoney.text = [NSString stringWithFormat:@"本单顾客实际支付:￥%@",dic[@"price"]];
    if(dic[@"point_pay"] &&([dic[@"point_pay"] intValue]>0)){
        _incomeMoney.text = [_incomeMoney.text stringByAppendingString:@" +"];
        _incomeIntegral.hidden = NO;
        _incomeIntegral.text = [NSString stringWithFormat:@"%@紫喇叭",dic[@"point_pay"]];
    }else{
        _incomeIntegral.hidden = YES;
    }
    
    if(array.count>0){
        
        UIImageView *leftImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dingd_icon3_default_nor.png"]];
        [self.contentView addSubview:leftImg];
        leftImg.sd_layout.topSpaceToView(_incomeMoney, 15).leftEqualToView(_incomeMoney).widthIs(GETWITH(28)).heightEqualToWidth();
        
        UILabel *good = [[UILabel alloc] init];
        good.font = _yjmoney.font;
        good.textColor = _yjmoney.textColor;
        good.text = @"商品";
        [self.contentView addSubview:good];
        good.sd_layout.leftSpaceToView(leftImg, GETWITH(26)).widthIs(40).heightIs(20).centerYEqualToView(leftImg);
        
        _anBtn = [[UIButton alloc] init];
       // anBtn.tag = indexPath.row;
        
        if([dic[@"isAN"] isEqualToString:@"0"]){
            
            [_anBtn setImage:[UIImage imageNamed:@"dingd_icon4_default_nor.png"] forState:UIControlStateNormal];
        }else if([dic[@"isAN"] isEqualToString:@"1"]){
            
           [_anBtn setImage:[UIImage imageNamed:@"dingd_icon5_default_nor.png"] forState:UIControlStateNormal];
        }
        [_anBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.contentView addSubview:_anBtn];
        
        _anBtn.sd_layout.rightSpaceToView(self.contentView, 5).widthIs(50).heightIs(20).centerYEqualToView(good);
        
      
        PayOrderDetails *orderTable = [[PayOrderDetails alloc] init];
        orderTable.data = array;
        orderTable.info = dic;
        CGFloat height = [self cellHeightGoods:array]+60;
        [self.contentView addSubview:orderTable];
        if([dic[@"isAN"] isEqualToString:@"0"]){
            orderTable.sd_layout.leftEqualToView(_incomeMoney).rightEqualToView(_anBtn).topSpaceToView(_anBtn, 0).heightIs(0);
        }else if([dic[@"isAN"] isEqualToString:@"1"]){
            orderTable.sd_layout.leftEqualToView(_incomeMoney).rightEqualToView(_anBtn).topSpaceToView(_anBtn, 10).heightIs(height);
        }
        //如果没有开通打印功能，商品订单不用显示打印
        NSDictionary *dicT = [userDefaults objectForKey:@"agentInfo"];
//        if([dicT[@"extend_fun"] rangeOfString:@"1"].location ==NSNotFound){
//            _bottmV.sd_layout.heightIs(40);
//            [_bottmV updateLayout];
//            _top1V.sd_layout.heightIs(0);
//            _top1V.hidden = YES;
//            [_top1V updateLayout];
//        }else{
//            if(![dic[@"pay_type"] isEqualToString:@"2"]){
//                UILabel *pay_typeLab = [[UILabel alloc] init];
//                pay_typeLab.textColor = UIColorFromRGB(0xfe9265);
//                pay_typeLab.text = @"店员收款";
//                [_top1V addSubview:pay_typeLab];
//
//            pay_typeLab.sd_layout.leftEqualToView(_userName).centerYEqualToView(_top1V).widthIs(150).autoHeightRatio(0);
//            }
//        }
        if([dicT[@"extend_fun"] rangeOfString:@"1"].location !=NSNotFound && [dic[@"can_refund"] isEqualToString:@"1"]){
            if(![dic[@"pay_type"] isEqualToString:@"2"]){
                UILabel *pay_typeLab = [[UILabel alloc] init];
                pay_typeLab.textColor = UIColorFromRGB(0xfe9265);
                pay_typeLab.text = @"店员收款";
                [_top1V addSubview:pay_typeLab];
                
            pay_typeLab.sd_layout.leftEqualToView(_userName).centerYEqualToView(_top1V).widthIs(150).autoHeightRatio(0);
            }

        }else if([dicT[@"extend_fun"] rangeOfString:@"1"].location !=NSNotFound && ![dic[@"can_refund"] isEqualToString:@"1"]){
            _refundBtn.hidden = YES;
            if(![dic[@"pay_type"] isEqualToString:@"2"]){
                UILabel *pay_typeLab = [[UILabel alloc] init];
                pay_typeLab.textColor = UIColorFromRGB(0xfe9265);
                pay_typeLab.text = @"店员收款";
                [_top1V addSubview:pay_typeLab];
                pay_typeLab.sd_layout.leftEqualToView(_userName).
                centerYEqualToView(_top1V).widthIs(150).autoHeightRatio(0);
            }

        }else if ([dicT[@"extend_fun"] rangeOfString:@"1"].location ==NSNotFound && ![dic[@"can_refund"] isEqualToString:@"1"]){
            _bottmV.sd_layout.heightIs(40);
            [_bottmV updateLayout];
            _top1V.sd_layout.heightIs(0);
            _top1V.hidden = YES;
            [_top1V updateLayout];
        }else if ([dicT[@"extend_fun"] rangeOfString:@"1"].location ==NSNotFound && [dic[@"can_refund"] isEqualToString:@"1"]){
           
            _printBtn.hidden = YES;
            _printBtn.sd_layout.widthIs(0);
            [_printBtn updateLayout];
            _refundBtn.sd_layout.rightSpaceToView(_printBtn,0);
            [_refundBtn updateLayout];
            
        }
        
    }else{
        if([dic[@"can_refund"] isEqualToString:@"1"]){
           _printBtn.hidden = YES;
            _printBtn.sd_layout.widthIs(0);
            [_printBtn updateLayout];
            _refundBtn.sd_layout.rightSpaceToView(_printBtn,0);
           [_refundBtn updateLayout];
            

        }else{
            _bottmV.sd_layout.heightIs(40);
            [_bottmV updateLayout];
            _top1V.sd_layout.heightIs(0);
            _top1V.hidden = YES;
            [_top1V updateLayout];
        }
    }
    
    if([dic[@"is_printer"] isEqualToString:@"1"]){
        UIImageView *printImge = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"print_bg01_deafult"]];
        printImge.frame = CGRectMake(0, 20, GETWITH(332), GETHEIGHT(258));
        printImge.centerX = self.contentView.centerX + 20;
        [self.contentView insertSubview:printImge atIndex:0];
    }

    if(dic[@"site_no"] && ((NSString *)dic[@"site_no"]).length){
        _siteNumber.text = dic[@"site_no"];
    }else{
        _siteView.hidden = YES;
    }
}

- (CGFloat)cellHeightGoods:(NSArray *)goods{
    CGFloat height = 0;
    for (NSDictionary *newdic in goods) {
        CGSize titleSize = [newdic[@"goods_name"] boundingRectWithSize:CGSizeMake(GETWITH(300), MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font14 } context:nil].size;
            height += (titleSize.height +16);
    }
    return height;
}

#pragma  mark ========打印订单========
- (void)stampOrder{
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Print/wpPrint" parameter:@{@"order_sn":_data[@"order_sn"]} successBlock:^(PPHttpRequest *request, id responseObj) {
        
        [AlertUtils showHint:@"打印成功"];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
       [AlertUtils showHint:errMsg];
    }];

}

#pragma  mark ========退款========
- (void)addRefundView{
    NSDictionary *dic = _data;
    NSArray *array = dic[@"goods_list"];
    if(array.count<1) {
        __weak typeof (self)weakself = self;
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请确认是否退款" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"退款" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             [self refund:@"" ordertype:@"2"];
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [[ToolClass viewController:weakself] presentViewController:alertController animated:YES completion:nil];
        
        return;
    }
    RefundView *refundView = [[RefundView alloc] initWithFrame:CGRectMake(0, 0,SCREEN_W, SCREEN_H) goodsInfo:array];
    [UIView animateWithDuration:0.5 animations:^{
        [[UIApplication sharedApplication].keyWindow addSubview:refundView];
    }];
    __weak typeof (self)weakself = self;
    refundView.selectBlock = ^(NSArray *selectArray) {
        NSString *str = @"";
        for (NSDictionary *dic in selectArray) {
            str = [NSString stringWithFormat:@"%@,%@",str,dic[@"goods_id"]];
        };
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请确认是否退款" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"退款" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           [weakself refund:str ordertype:@"1"];
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [[ToolClass viewController:weakself] presentViewController:alertController animated:YES completion:nil];
    };
    
}

-(void)refund:(NSString *)goods_ids ordertype:(NSString *)type{
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Order/refundOrder" parameter:@{@"order_sn":_data[@"order_sn"],@"goods_ids":goods_ids,@"order_type":type} successBlock:^(PPHttpRequest *request, id responseObj) {
        
        [AlertUtils showHint:@"退款成功"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RefundSucceed" object:nil];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showHint:errMsg];
    }];
}

@end
